<template>
  <a-card>
    <!-- 查询条件 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <div class="collapseArea_header">
          <a-row :gutter="48">
            <a-col @click.stop="() => {}" :md="6" :sm="24">
              <a-form-item label="执法机关名称：">
                <a-input v-model="queryParam.f_title" placeholder="请输入执法机关名称" allowClear />
              </a-form-item>
            </a-col>
            <a-col @click.stop="() => {}" :md="6" :sm="24">
              <a-form-item label="执法类别名称：">
                <a-input v-model="queryParam.f_title" placeholder="请输入执法类别名称" allowClear />
              </a-form-item>
            </a-col>

            <a-col @click.stop="() => {}" :md="6" :sm="24">
              <a-form-item label="执法机关层级：">
                <a-select
                  v-model="queryParam.f_pubunitid"
                  placeholder="请选择执法机关层级"
                  allowClear
                  showSearch
                  :filter-option="filterOption"
                >
                  <a-select-option v-for="item in unitList" :key="item.id" :value="item.id">
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>

            <a-col :md="6" :sm="24">
              <a-button type="primary" style="margin-left: 20px" @click.stop="queryList(queryParam)" icon="search"
                >查询</a-button
              >
              <a-button icon="reload" style="margin-left: 8px" @click.stop="reQuery">重置</a-button>
            </a-col>
          </a-row>
        </div>
        <!-- 导出按钮 -->
        <div style="margin-bottom: 16px; margin-top: 10px">
          <a-button type="primary" class="m-l-8;padding-right:20px" @click="addHandleData" icon="plus"
            >新增执法机构</a-button
          >
        </div>
      </a-form>
    </div>

    <!-- 自定义表头组件 -->
    <HEADERDEFINITION ref="headerDefRef" :ucolumns="ucolumns" @f_setColumns="s_setColumns" />
    <div class="headerdefBox">
      <a-tooltip placement="topLeft">
        <template slot="title">
          <span>重置表格</span>
        </template>
        <img @click="resetting()" style="margin-right: 16px" src="@/assets/icons/table/table_refresh.png" alt="重置" />
      </a-tooltip>

      <a-tooltip placement="topLeft">
        <template slot="title">
          <span>设置表格</span>
        </template>
        <img @click="showHeaderDef($event)" src="@/assets/icons/table/table_config.png" alt="表格设置" />
      </a-tooltip>
    </div>

    <!-- 表格数据 -->
    <a-table
      :scroll="{ x: 1000, y: 520 }"
      :columns="ucolumns"
      :data-source="listData"
      :pagination="upagination"
      :loading="loading"
      rowKey="id"
      @change="tableChange"
      size="middle"
      :bordered="ubordered"
      :rowClassName="rowClassName"
    >
      <span slot="serial" slot-scope="text, record, index">
        {{ (upagination.current - 1) * upagination.pageSize + parseInt(index) + 1 }}
      </span>

      <div slot="typeSlot" slot-scope="type" class="overBox" style="width: 100%">
        <a-tooltip placement="topLeft">
          <template slot="title">
            <span>{{ typeLable(type) }}</span>
          </template>
          {{ typeLable(type) }}
        </a-tooltip>
      </div>

      <div slot="statusSlot" slot-scope="status" class="overBox" style="width: 100%">
        <a-tooltip placement="topLeft">
          <template slot="title">
            <span>{{ statusLable(status) }}</span>
          </template>
          {{ statusLable(status) }}
        </a-tooltip>
      </div>

      <div slot="sourceSlot" slot-scope="source" class="overBox" style="width: 100%">
        <a-tooltip placement="topLeft">
          <template slot="title">
            <span>{{ sourceLable(source) }}</span>
          </template>
          {{ sourceLable(source) }}
        </a-tooltip>
      </div>

      <div slot="titleSlot" slot-scope="title" class="overBox" style="width: 100%">
        <a-tooltip placement="topLeft">
          <template slot="title">
            <span>{{ title }}</span>
          </template>
          {{ title }}
        </a-tooltip>
      </div>

      <div slot="pubcodeSlot" slot-scope="pubcode" class="overBox" style="width: 100%">
        <a-tooltip placement="topLeft">
          <template slot="title">
            <span>{{ pubcode }}</span>
          </template>
          {{ pubcode }}
        </a-tooltip>
      </div>

      <span slot="operation" slot-scope="text, record">
        <template>
          <a @click="lawDetail(record)">详情</a>
          <a-divider type="vertical" />
          <a @click="editHandleData(record)">编辑</a>
          <a-divider type="vertical" />
          <a @click="uploadFile(record)">上传附件</a>
          <a-divider type="vertical" v-if="hasFile(record)" />
          <a @click="downloadFile(record)" v-if="hasFile(record)">下载附件</a>
        </template>
      </span>
    </a-table>

    <!-- 导入数据弹窗 -->
    <a-modal
      title="上传法律法规文件"
      v-model="importVisible"
      destroyOnClose
      @cancel="importCancel"
      @ok="handleImportOk"
      :maskClosable="false"
    >
      <a-alert type="info" show-icon>
        <span slot="message"> 请按照对应格式上传法律法规文件 </span>
      </a-alert>
      <br />
      <a-upload-dragger
        name="file"
        accept=".doc,.docx"
        @reject="handleImportReject"
        :before-upload="beforeImportUpload"
        :show-upload-list="false"
        :multiple="true"
      >
        <div v-if="importFile.name">
          <a-row class="l-h-25">
            <a-col :span="8" class="p-r-10">
              <p class="ant-upload-drag-icon m-b-0">
                <a-icon type="file" />
              </p>
            </a-col>
            <a-col :span="16" class="text-left">
              <p class="ant-upload-hint">
                {{ importFile.name }}
              </p>
              <p class="ant-upload-hint">将文件拖到此处或点击此处重新上传</p>
            </a-col>
          </a-row>
        </div>
        <div v-else>
          <p class="ant-upload-drag-icon m-b-0">
            <a-icon type="cloud-upload" />
          </p>
          <p class="ant-upload-hint">您可以将文件拖到此处或点击此处上传</p>
          <p class="ant-upload-hint">文件格式为doc,docx</p>
        </div>
      </a-upload-dragger>
      <br />
    </a-modal>

    <a-drawer
      :title="isEdit ? '编辑法律法规' : '添加法律法规'"
      width="38%"
      :visible="visible_edit"
      :body-style="{ paddingBottom: '80px' }"
      @close="visible_edit = false"
      destroyOnClose
    >
      <LawInfoAdd
        ref="edit"
        @close="visible_edit = false"
        @reloadList="queryList"
        :unitList="unitList"
        :infoForm="infoForm"
      ></LawInfoAdd>
    </a-drawer>
  </a-card>
</template>
<script>
import Tp_agy_class from '@/enumeration/Tp_agy_class.js'
import Tp_yesno from '@/enumeration/YesNo.js'
import Tp_bl_aera from '@/enumeration/Tp_bl_aera.js'
import { queryInfo_force_unitList } from '@/api/info/info_force_unit'
import { getLawDocPage, uploadLawFile } from '@/api/law/law_doc'
import { Tp_lawList } from '@/enumeration/Tp_law'
import { Tp_lawsrcList } from '@/enumeration/Tp_lawsrc'
import { St_lawList } from '@/enumeration/St_law'
import { Tp_provision } from '@/enumeration/Tp_provision'
import { getUrl } from '@/api/base/file.js'
import storage from 'store'
import { APP_USER } from '@/store/mutation-types.js'
export default {
  data () {
    return {
      Tp_agy_class: Tp_agy_class, // Tp_agy_class枚举值，用于状态判断或者参数传值
      collapseKey: [], // 折叠面板key
      ucolumns: [
        {
          title: '序号',
          width: '50px',
          align: 'center',
          fixed: 'left',
          scopedSlots: { customRender: 'serial' }
        },

        {
          title: '执法机关名称',
          dataIndex: 'agy_name',
          width: '1',
          sorter: (a, b) => String(a.agy_name).localeCompare(String(b.agy_name)),
          align: 'center'
        },
        {
          title: '执法机关类别',
          dataIndex: 'agy_ct_text',
          width: '1',
          align: 'center',
          sorter: (a, b) => a.agy_ct_text.localeCompare(b.agy_ct_text)
        },
        {
          title: '执法机关层级',
          dataIndex: 'agy_class_text',
          width: '1',
          align: 'center',
          sorter: (a, b) => a.agy_class_text.localeCompare(b.agy_class_text)
        },
        {
          title: '执法类别',
          dataIndex: 'agy_type',
          width: '1',
          sorter: (a, b) => String(a.agy_type).localeCompare(String(b.agy_type)),
          align: 'center'
        },
        {
          title: '编制人数',
          dataIndex: 'org_num',
          width: '1',
          sorter: (a, b) => a.org_num - b.org_num,
          align: 'center'
        },
        {
          title: '是否公开',
          dataIndex: 'public_is_text',
          width: '1',
          align: 'center',
          sorter: (a, b) => a.public_is_text.localeCompare(b.public_is_text)
        },
        {
          title: '是否直属',
          dataIndex: 'directly_text',
          width: '1',
          align: 'center',
          sorter: (a, b) => a.directly_text.localeCompare(b.directly_text)
        },
        {
          title: '联系人姓名',
          dataIndex: 'link_name',
          width: '1',
          sorter: (a, b) => String(a.link_name).localeCompare(String(b.link_name)),
          align: 'center'
        },
        {
          title: '联系人电话',
          dataIndex: 'link_phone',
          width: '1',
          sorter: (a, b) => String(a.link_phone).localeCompare(String(b.link_phone)),
          align: 'center'
        },
        {
          title: '详细地址',
          dataIndex: 'link_addr',
          width: '1',
          sorter: (a, b) => String(a.link_addr).localeCompare(String(b.link_addr)),
          align: 'center'
        },
        {
          title: '所在部门id',
          dataIndex: 'secid',
          width: '1',
          sorter: (a, b) => String(a.secid).localeCompare(String(b.secid)),
          align: 'center'
        },
        {
          title: '所属区域',
          dataIndex: 'bl_aera_text',
          width: '1',
          align: 'center',
          sorter: (a, b) => a.bl_aera_text.localeCompare(b.bl_aera_text)
        },
        {
          title: '设定依据',
          dataIndex: 'rely',
          width: '1',
          sorter: (a, b) => String(a.rely).localeCompare(String(b.rely)),
          align: 'center'
        },
        {
          title: '执法证编号范围',
          dataIndex: 'force_sco',
          width: '1',
          sorter: (a, b) => String(a.force_sco).localeCompare(String(b.force_sco)),
          align: 'center'
        },
        {
          title: '监督证编号范围',
          dataIndex: 'code_sco',
          width: '1',
          sorter: (a, b) => String(a.code_sco).localeCompare(String(b.code_sco)),
          align: 'center'
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: '150px',
          fixed: 'right',
          scopedSlots: { customRender: 'operation' }
        }
      ], // 表头
      queryParam: {
        f_agy_name: '', //执法机关名称
        f_agy_ct: undefined, // 执法类别
        f_agy_class: undefined, // 法律发布机关
        f_agy_type: undefined, //来源途径
        f_org_num: '', //发布文号
        f_public_is: undefined, //有效性
        f_directly: null, // 发布开始日期
        f_link_name: null, //
        f_link_phone: null, // 施行开始日期
        f_link_addr: null, //
        f_bl_aera: null, // 失效开始日期
        f_rely: null,
        f_force_sco: null, // 收录开始日期
        f_code_sco: null,
        pageNumber: 1,
        pageSize: 10,
        sort: 'id',
        order: 'desc'
      },
      listData: [],
      upagination: {
        // 表格分页参数
        defaultPageSize: 20,
        total: 0,
        current: 1,
        pageSize: 10,
        showTotal: total => `共${total}条数据`,
        showSizeChanger: true,
        pageSizeOptions: ['10', '20', '50', '100']
      },
      loading: false,
      ubordered: true, // 表格边框是否显示
      currentUser: storage.get(APP_USER), // 登录人信息
      unitList: [], // 发布机关查询数据
      Tp_lawList: Tp_lawList, // 执法类别
      lawTypeList: [], // 执法类别下拉框数据
      Tp_lawsrcList: Tp_lawsrcList, // 来源途径
      lawSrcTypeList: [], //来管途径下拉框数据
      St_lawList: St_lawList, // 法律有效性
      lawValidTypeList: [], //法律有效性下拉框数据
      Tp_provision: Tp_provision, //法律条文类别
      importVisible: false, // 导入文件模态框
      importFile: {}, // 上传文件
      selectLawData: {}, //上传文件选择的法律文件
      visible_edit: false,
      isEdit: false,
      infoForm: {
        id: '',
        title: '',
        type: undefined,
        pubunitid: undefined,
        pubdate: undefined,
        execdate: undefined,
        status: undefined,
        losedate: undefined,
        recorddate: undefined,
        source: undefined,
        pubcode: '',
        isAdd: true
      }
    }
  },
  components: {
    HEADERDEFINITION: () => import('@/views/customComponents/headerDefinition.vue'),
    LawInfoAdd: () => import('@/views/lawInfo/law/LawInfoAdd.vue')
  },
  computed: {},
  created () {
    this.queryParam.reguserid = this.currentUser.userId
    this.lawTypeList = Tp_lawList
    this.lawSrcTypeList = Tp_lawsrcList
    this.lawValidTypeList = St_lawList
    console.log(this.Tp_agy_class)
    this.queryUnitList() //查询发布机关数据
    this.queryList()
  },
  updated () {},
  methods: {
    // 重置表头方法
    resetting () {
      this.$refs.headerDefRef.f_resetting()
    },
    // 子组件回调函数, 重置表头
    s_setColumns (columns) {
      this.ucolumns = columns
    },
    // 显示自定义表头组件
    showHeaderDef (e) {
      this.$refs.headerDefRef.f_init(e)
    },

    filterOption (input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },

    // 新增页面
    addHandleData () {
      this.isEdit = false
      this.visible_edit = true
      this.infoForm = {
        id: '',
        title: '',
        type: undefined,
        pubunitid: undefined,
        pubdate: undefined,
        execdate: undefined,
        status: undefined,
        losedate: undefined,
        recorddate: undefined,
        source: undefined,
        pubcode: '',
        isAdd: true
      }
      this.$nextTick(() => {
        this.$refs.edit.resetForm()
      })
    },
    // 编辑数据
    editHandleData (record) {
      this.isEdit = true
      this.visible_edit = true
      this.infoForm.id = record.id
      this.infoForm.title = record.title
      this.infoForm.type = record.type
      this.infoForm.pubunitid = record.pubunitid
      this.infoForm.pubdate = record.pubdate
      this.infoForm.execdate = record.execdate
      this.infoForm.status = record.status
      this.infoForm.losedate = record.losedate
      this.infoForm.recorddate = record.recorddate
      this.infoForm.source = record.source
      this.infoForm.pubcode = record.pubcode
      this.infoForm.isAdd = false
    },
    /**
     * 重置查询条件并查询数据
     */
    reQuery () {
      ;(this.queryParam = {
        f_agy_name: '', //执法机关名称
        f_agy_ct: undefined, // 执法类别
        f_agy_class: undefined, // 法律发布机关
        f_agy_type: undefined, //来源途径
        f_org_num: '', //发布文号
        f_public_is: undefined, //有效性
        f_directly: null, // 发布开始日期
        f_link_name: null, //
        f_link_phone: null, // 施行开始日期
        f_link_addr: null, //
        f_bl_aera: null, // 失效开始日期
        f_rely: null,
        f_force_sco: null, // 收录开始日期
        f_code_sco: null,
        pageNumber: 1,
        pageSize: 10,
        sort: 'id',
        order: 'desc'
      }),
        this.queryList()
    },
    // 查询全部执法机关层级
    async queryUnitList () {
      await queryInfo_force_unitList(this.queryParam).then(res => {
        // console.log('查询参数', res)
        if (res.code == 0 && res.data) {
          this.unitList = res.data
        } else {
          this.unitList = []
        }
      })
    },

    tableChange (upagination, filters, sorter, { currentDataSource }) {
      this.row_idx = upagination.current * upagination.pageSize - upagination.pageSize
      this.queryParam.pageNumber = upagination.current
      this.queryParam.pageSize = upagination.pageSize
      this.queryList()
    },
    // 接收时间监听判断开始结束日期是否合理
    pubDateListen () {
      if (
        this.queryParam.f_pubStartDate > this.queryParam.f_pubEndDate &&
        this.queryParam.f_pubStartDate &&
        this.queryParam.f_pubEndDate
      ) {
        this.queryParam.f_pubStartDate = undefined
      }
    },
    execDateListen () {
      if (
        this.queryParam.f_execStartDate > this.queryParam.f_execEndDate &&
        this.queryParam.f_execStartDate &&
        this.queryParam.f_execEndDate
      ) {
        this.queryParam.f_execStartDate = undefined
      }
    },
    loseDateListen () {
      if (
        this.queryParam.f_loseStartDate > this.queryParam.f_loseEndDate &&
        this.queryParam.f_loseStartDate &&
        this.queryParam.f_loseEndDate
      ) {
        this.queryParam.f_loseStartDate = undefined
      }
    },
    recordDateListen () {
      if (
        this.queryParam.f_recordStartDate > this.queryParam.f_recordEndDate &&
        this.queryParam.f_recordStartDate &&
        this.queryParam.f_recordEndDate
      ) {
        this.queryParam.f_recordStartDate = undefined
      }
    },

    /**
     * 执法类别显示转换
     */
    typeLable (val) {
      for (let key in this.Tp_lawList) {
        if (this.Tp_lawList[key].value == val) {
          return this.Tp_lawList[key].name
        }
      }
      return val
    },
    /**
     * 有效性显示转换
     */
    statusLable (val) {
      for (let key in this.St_lawList) {
        if (this.St_lawList[key].value == val) {
          return this.St_lawList[key].name
        }
      }
      return val
    },
    /**
     * 来源途径显示转换
     */
    sourceLable (val) {
      for (let key in this.Tp_lawsrcList) {
        if (this.Tp_lawsrcList[key].value == val) {
          return this.Tp_lawsrcList[key].name
        }
      }
      return val
    },

    queryList () {
      // 时间转换
      let cpQueryParam = JSON.parse(JSON.stringify(this.queryParam))
      if (this.queryParam.pubStartDate?.format) {
        cpQueryParam.pubStartDate = this.queryParam.pubStartDate.format('YYYY-MM-DD') + ' 00:00:00'
      }
      if (this.queryParam.pubEndDate?.format) {
        cpQueryParam.pubEndDate = this.queryParam.pubEndDate.format('YYYY-MM-DD') + ' 23:59:59'
      }
      if (this.queryParam.execStartDate?.format) {
        cpQueryParam.execStartDate = this.queryParam.execStartDate.format('YYYY-MM-DD') + ' 00:00:00'
      }
      if (this.queryParam.execEndDate?.format) {
        cpQueryParam.execEndDate = this.queryParam.execEndDate.format('YYYY-MM-DD') + ' 23:59:59'
      }
      if (this.queryParam.loseStartDate?.format) {
        cpQueryParam.loseStartDate = this.queryParam.loseStartDate.format('YYYY-MM-DD') + ' 00:00:00'
      }
      if (this.queryParam.loseEndDate?.format) {
        cpQueryParam.loseEndDate = this.queryParam.loseEndDate.format('YYYY-MM-DD') + ' 23:59:59'
      }
      if (this.queryParam.recordStartDate?.format) {
        cpQueryParam.recordStartDate = this.queryParam.recordStartDate.format('YYYY-MM-DD') + ' 00:00:00'
      }
      if (this.queryParam.recordEndDate?.format) {
        cpQueryParam.recordEndDate = this.queryParam.recordEndDate.format('YYYY-MM-DD') + ' 23:59:59'
      }
      if (this.queryParam.f_title) {
        cpQueryParam.f_title = this.queryParam.f_title.toString().trim()
      }
      if (this.queryParam.f_pubcode) {
        cpQueryParam.f_pubcode = this.queryParam.f_pubcode.toString().trim()
      }
      this.loading = true
      getLawDocPage(cpQueryParam)
        .then(res => {
          if (res.code !== 0) {
            this.$message.error('获取数据失败')
          } else {
            this.listData = res.data.records
            this.upagination.total = res.data.total
            this.upagination.current = res.data.current
            this.upagination.pageSize = res.data.size
          }
        })
        .catch(err => {
          this.listData = []
          console.log(err, '获取数据失败')
        })
        .finally(() => {
          this.loading = false
        })
    },
    // 判断是否上传了文件
    hasFile (record) {
      if (record.fileid != null && record.fileid != '' && record.fileid != undefined) {
        return true
      } else {
        return false
      }
    },
    uploadFile (record) {
      this.selectLawData = record
      this.importVisible = true
    },
    // 导入文件
    handleImportOk () {
      // 调用上传接口获取保存的fileId,
      if (!this.importFile) {
        this.$message.warning('请添加上传文件')
        return
      }
      let _this = this
      this.$confirm({
        title: '确定上传吗？',
        onOk: () => {
          this.confirmLoading = true
          uploadLawFile({ id: _this.selectLawData.id }, _this.importFile).then(res => {
            if (res.code == 0) {
              _this.importVisible = false
              _this.confirmLoading = false
              _this.$message.success('上传成功')
              _this.queryList()
              _this.importFile = {}
            } else {
              _this.$message.error('上传失败')
            }
          })
        }
      })
    },
    importCancel () {
      this.selectLawData = undefined
      this.importFile = {}
    },
    /**
     * 拖拽验证文件类型
     */
    handleImportReject (file) {
      this.beforeImportUpload(file)
    },
    /**
     * 上传导入文件前验证文件类型
     */
    beforeImportUpload (file) {
      return new Promise((resolve, reject) => {
        //文件格式是否为doc、docx
        let isAcceptType = file.name.toLowerCase().substr(file.name.lastIndexOf('.'))
        let acceptType = 'doc、docx'
        if (!(isAcceptType == '.doc' || isAcceptType == '.docx')) {
          this.$message.warning('请上传' + acceptType + '格式文件')
          return reject(false)
        }
        //文件小于20M
        let isLtSize = file.size / 1024 / 1024 < 20
        if (!isLtSize) {
          this.$message.warning('请上传20MB以内的文件')
          return reject(false)
        }
        this.importFile = file
        return resolve(false)
      })
    },
    // 下载文件
    downloadFile (record) {
      getUrl({ id: record.fileid }).then(res => {
        if (res.code == 0) {
          window.open(res.data)
        } else {
          this.$message.error('获取文件下载地址失败')
        }
      })
    },
    // 查询详情
    lawDetail (record) {
      // 格式化对应的显示数据
      let newRecord = JSON.parse(JSON.stringify(record))
      newRecord.type_text = this.typeLable(newRecord.type) // 执法类别
      newRecord.status_text = this.statusLable(newRecord.status) // 有效性
      newRecord.source_text = this.sourceLable(newRecord.source) // 来源途径
      this.$router.push({
        path: '/LawInfoDetail',
        query: {
          params: newRecord
        }
      })
    },
    rowClassName (record, index) {
      return index % 2 === 0 ? 'oddRow' : 'evenRow'
    }
  }
}
</script>

<style lang="less" scoped>
@import '~@/components/TableDrag/style.less';

.label-div {
  padding: 10px;
  height: 100%;
  display: inline-block;
  width: 100%;
}

.label-title {
  float: left;
  font-size: 16px;
  font-weight: bold;
}
.add-btn {
  float: right;
  margin-right: 20px;
}
.input-single {
  width: 200px;
}

.headerdefBox img {
  height: 20px;
  width: 20px;
}
.headerdefBox {
  // border: 1px solid red;
  margin: 0 10px 10px 0;
  display: flex;
  justify-content: end;
}
.formArea {
  margin-bottom: 30px;
}

.collapseArea {
  border: none;
  .ant-collapse-item {
    border-bottom: none;
  }
  /deep/.ant-collapse-content {
    border-top: none;
  }
}
/deep/ .ant-collapse-header {
  background-color: #fff;
}
.collapseArea_header {
  .ant-form-item {
    margin-bottom: 0;
  }
}

.collapseArea_body {
  padding-top: 10px;
  padding: 0 20px 0 0px;
}

.overBox {
  width: 90%;
  overflow: hidden; /*超出部分隐藏*/
  white-space: nowrap; /*不换行*/
  text-overflow: ellipsis; /*超出部分文字以...显示*/
}
</style>
